package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.util.validation.metadata.NamedObject;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * @author blh
 * @date 2024年06月21日 19:02
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    @ApiOperation("新增用户接口")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userFormDTO) {
        // 把DTO拷贝成PO
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        // 新增
        userService.save(user);
        // 删除
    }

    @ApiOperation("删除用户接口")
    @DeleteMapping("{id}")
    public void deleteUserById(@ApiParam("用户Id") @PathVariable("id") Long id){
        userService.removeById(id);
    }

    @ApiOperation("根据Id查询用户接口")
    @GetMapping("{id}")
    public UserVO queryUserById(@ApiParam("用户Id") @PathVariable("id") Long id){

        return userService.queryUserAndAddressById(id);

    }

    @ApiOperation("根据Id批量查询用户接口")
    @GetMapping()
    public List<UserVO> queryUserById(@ApiParam("用户Id") @RequestParam("ids") List<Long> ids){

        return userService.queryUserAndAddressByIds(ids);
    }

    @ApiOperation("扣减用户余额接口")
    @PutMapping("/{id}/deduction/{money}")
    public void deductMoneyById(@ApiParam("用户Id") @PathVariable("id") Long id,
                                @ApiParam("扣减金额") @PathVariable("money") Integer money){
        userService.deductMoneyById(id, money);
    }

    // get对象请求可以由对象接受
    @ApiOperation("根据复杂条件查询")
    @GetMapping("/list")
    public List<UserVO> queryUsers(UserQuery query){

        // 查询用户PO
        List<User> users = userService.queryUsers(query.getName(), query.getStatus(), query.getMinBalance(), query.getMaxBalance());
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @ApiOperation("根据复杂条件分页查询")
    @GetMapping("/page")
    public PageDTO<UserVO> queryUsersPage(UserQuery query){

        return userService.queryUsersPage(query);
    }

}
